package controllers

import (
	"article/models"
	beego "github.com/beego/beego/v2/server/web"
)

type ArticleController struct {
	beego.Controller
}

type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *ArticleController) Add() {
	title := c.GetString("title")
	status := c.GetString("status")
	fb := c.GetString("fb")
	pl := c.GetString("pl")
	time := c.GetString("time")
	article := models.Article{
		Title:  title,
		Status: status,
		Fb:     fb,
		Pl:     pl,
		Time:   time,
	}
	err := models.DB.Create(&article).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "添加成功",
			Data: article,
		}
		c.ServeJSON()
	}
}

func (c *ArticleController) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	var count int64
	models.DB.Model(&models.Article{}).Count(&count)
	offset := (page - 1) * size

	where := make(map[string]interface{})
	title := c.GetString("title")
	if title != "" {
		where[title] = "title"
	}

	var article []models.Article
	err := models.DB.Offset(offset).Limit(size).Order("id").Find(&article).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "展示失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "展示成功",
			Data: article,
		}
		c.ServeJSON()
	}
}
